/*************************************************************************
	> File Name: shmClient.cc
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/09/12 14:47
 ************************************************************************/

#include "comm.hpp"

int main(int argc, char *argv[])
{
    key_t k = ftok(PATH_NAME, PROJ_ID);
    if (k < 0) {
        Log("Create key fail", Error) << " client key:" << k << std::endl;
        exit(1);
    }
        Log("Create key success", Debug) << " client key:" << k << std::endl;
    int shmid = shmget(k, SHM_SIZE, 0);
    if (shmid < 0) {
        Log("Create shm fail", Error) << " client key:" << k << std::endl;
        exit(2);
    }
    Log("Create shm success", Error) << " client key:" << k << std::endl;
    char* shmaddr = (char*)shmat(shmid, nullptr, 0);
    if (!shmaddr) {
        Log("Attach shm fail", Error) << " client key:" << k << std::endl;
        exit(3);
    }
    Log("Attach shm success", Error) << " client key:" << k << std::endl;
    int fd = OpenFIFO(FIFO_NAME, WRITE);
    while (1) {
        ssize_t s = read(0, shmaddr, SHM_SIZE - 1);
        if (s > 0) {
            shmaddr[s - 1] = 0;
            Signal(fd);
            if (strcmp(shmaddr, "quit") == 0) {
                break;
            }
        }
    }
    CloseFifo(fd);
    int n = shmdt(shmaddr);
    assert(n != -1);
    Log("Detach shm success", Error) << " client key:" << k << std::endl;
    sleep(3);
    return 0;
}



